﻿function LanguageViewModel() {
    var self = this;

    // knockout variables
    self.languages = ko.observableArray([]);
    self.workingLanguage = ko.observable(null);

    self.selectLanguage = function (language) {
        self.workingLanguage(language);
    };
    self.deselectLanguage = function () {
        self.workingLanguage(null);
    };
    self.selectWorkingLanguage = function (language) {
        self.selectLanguage(language);
    };
    self.selectNewLanguage = function () {
        var newLanguage = new Language({});
        self.languages.push(newLanguage);
        self.selectLanguage(newLanguage);
    };

    //CRUD OPERATIONS
    self.saveNewLanguage = function () {
        $.ajax({
            url: "/Language/Save",
            type: 'post',
            data: ko.toJSON(self.workingLanguage()),
            contentType: 'application/json',
            success: function (id) {
                self.workingLanguage().Id(id);
                self.deselectLanguage();
                $("#CreateLanguage").modal("hide");
            }
        });
    };
    self.saveEditLanguage = function () {
        $.ajax({
            url: "/Language/Save",
            type: 'post',
            data: ko.toJSON(self.workingLanguage()),
            contentType: 'application/json',
            success: function () {
                self.deselectLanguage();
                $("#EditLanguage").modal("hide");
            }
        });
    };
    self.deleteLanguage = function () {
        $.post("/Language/DeleteLanguage", { id: self.workingLanguage().Id() }, function () {
            self.languages.pop(self.workingLanguage());
            self.deselectLanguage();
        });
        $('#DeleteLanguage').modal('hide');
    };
    self.cancelNewLanguage = function () {
        self.deselectLanguage();
        self.languages.pop(self.workingLanguage());
        $('#CreateLanguage').modal('hide');
    };
    self.cancelEditLanguage = function () {
        self.deselectLanguage();
        $('#EditLanguage').modal('hide');
    };
    self.cancelDetailsLanguage = function () {
        self.deselectLanguage();
        $('#DetailsLanguage').modal('hide');
    };
    self.cancelDeleteLanguage = function () {
        self.deselectLanguage();
        $('#DeleteLanguage').modal('hide');
    };

    self.loadLanguages = function () {
        $.getJSON("/Language/GetJsonLanguage", function (allData) {
            var mappedLanguages = $.map(allData, function (item) { return new Language(item); });
            self.languages(mappedLanguages);
        });
    };

}